package com.mnt.washio.utils.network.ws;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class GetBalanceWSControl extends BaseWSControl {
	String userId;

	public GetBalanceWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId) {
		super(context, listener, WebServiceFlag.GET_BALANCE);
		this.userId = userId;
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.WASHIO_WS_URL + "account/balance/" + userId;
		try {
			String respone = NetworkUtils.doRequest(url);
			return getCoupon(respone);

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	private Float getCoupon(String json) {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if (jsonObject.has("error")) {
				mError = jsonObject.getString("error");
				return null;
			}
			if (jsonObject.has("balance")) {
				return Float.parseFloat(jsonObject.get("balance").toString());
			}
			return null;
		} catch (Exception e) {
			mError = e.getMessage();
			return null;
		}
	}

}
